package com.source.interceptor;
import com.alibaba.fastjson.JSON;
import com.source.sys.entity.Popedom;
import com.source.sys.service.PopedomService;
import com.source.sys.service.RolePopedomService;
import com.source.utils.CommonResult;
import com.source.utils.JwtUtils;
import com.source.utils.ResponseUtils;
import com.source.utils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * @Author ZZF
 * @Time 2021/03/16 15:36
 * @Decription 需要登录权限的拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization");
        JwtUtils jwtUtils = new JwtUtils();
        //解决乱码问题
        ResponseUtils.solveEncoding(request, response);

//        if(request.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.toString())){
//            //用OPTIONS方法请求
//            return false;
//        }
        //获取Authorization的请求头
        String token = request.getHeader("Authorization");
        if(token == null){
            ResponseUtils.write(response,new CommonResult(ResultEnum.ERROR.getCode(),"缺少请求头参数Authorization"));
            return false;
        }
        if(!jwtUtils.checkToken(token) || jwtUtils.checkTokenExpired(token)){
            //不匹配或过期
            ResponseUtils.write(response,new CommonResult(ResultEnum.ERROR.getCode(),"请重新登录"));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
